<template>
    <div class="app-container">
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                    v-hasPermi="['system:role:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
                    @click="handleMutipleDelete" v-hasPermi="['system:role:remove']">删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-tooltip class="item" effect="dark" content="刷新" placement="right">
                    <el-button icon="el-icon-refresh" circle size="mini" @click="refresh" :loading="isRefresh"></el-button>
                </el-tooltip>
            </el-col>
        </el-row>

        <el-table v-loading="loading" :data="roleList" @selection-change="handleSelectionChange" stripe
            :default-sort="{ prop: 'id', order: 'ascending' }" @sort-change="sortChange">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="编号" prop="id" width="80" align="center" sortable />
            <el-table-column label="岗位名称" prop="name" :show-overflow-tooltip="true" width="150" align="center" />
            <el-table-column label="年龄" prop="age" :show-overflow-tooltip="true" width="80" align="center" sortable />
            <el-table-column label="最低学历" prop="education" :show-overflow-tooltip="true" width="100" align="center"
                sortable="custom" />
            <el-table-column label="任职要求" prop="skills" :show-overflow-tooltip="true" width="200" align="center" />
            <el-table-column label="岗位描述" prop="descriptions" :show-overflow-tooltip="true" width="250" align="center" />
            <el-table-column label="工作经验" prop="workExperience" :show-overflow-tooltip="true" width="100" align="center"
                sortable />
            <el-table-column label="岗位薪资(元)" prop="salaryRange" :show-overflow-tooltip="true" width="150" align="center" />
            <el-table-column label="匹配简历" prop="deliver" :show-overflow-tooltip="true" width="100" align="center"
                sortable />
            <!-- <el-table-column label="提交时间" align="center" prop="createTime" width="180">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.createTime) }}</span>
                </template>
            </el-table-column> -->
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope" v-if="scope.row.roleId !== 1">
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                        v-hasPermi="['system:role:edit']">修改</el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                        v-hasPermi="['system:role:remove']">删除</el-button>
                    <el-button size="mini" type="text" icon="el-icon-search" @click="handleSee(scope.row)"
                        v-hasPermi="['system:role:remove']">查看简历</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
            @pagination="getList" />

        <!-- 添加或修改角色配置对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="140px" label-position="left">
                <el-form-item label="岗位名称" prop="name">
                    <el-input v-model="form.name" />
                </el-form-item>
                <el-form-item label="年龄上限" prop="age">
                    <el-input v-model="form.age" type="number" min="18" max="100" />
                </el-form-item>
                <el-form-item label="最低学历" prop="education">
                    <el-select v-model="form.education">
                        <el-option v-for="item in educationOptions" :key="item.value" :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="任职要求" prop="skills">
                    <el-input v-model="form.skills" type="textarea" :rows="4" />
                </el-form-item>
                <el-form-item label="岗位描述" prop="descriptions">
                    <el-input v-model="form.descriptions" type="textarea" :rows="4" />
                </el-form-item>
                <el-form-item label="工作经验（年）" prop="workExperience">
                    <el-input v-model="form.workExperience" type="number" min="0" max="30" />
                </el-form-item>
                <el-form-item label="岗位薪资（元）" prop="salaryRange">
                    <el-slider v-model="form.salaryRange" range :max="50000" :step="500">
                    </el-slider>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <el-dialog :title="resumeTitle" :visible.sync="resumeOpen" width="880px" append-to-body>
            <el-table v-loading="loading" :data="resumeOpenList">
                <el-table-column label="编号" prop="id" width="50" />
                <el-table-column label="姓名" prop="name" :show-overflow-tooltip="true" width="110" />
                <el-table-column label="年龄" prop="age" :show-overflow-tooltip="true" width="50" />
                <el-table-column label="性别" prop="sex" :show-overflow-tooltip="true" width="50" />
                <el-table-column label="联系方式" prop="phone" :show-overflow-tooltip="true" width="150" />
                <el-table-column label="工作经验(年)" prop="workTime" :show-overflow-tooltip="true" width="110" />
                <!-- <el-table-column label="投递岗位" prop="targetPosition" :show-overflow-tooltip="true" width="115" /> -->
                <el-table-column label="最高学历" prop="education" :show-overflow-tooltip="true" width="115" />
                <el-table-column label="毕业院校" prop="school" :show-overflow-tooltip="true" width="200">

                </el-table-column>
                <!-- <el-table-column label="人才画像" prop="talentPortrait" :show-overflow-tooltip="true" width="200">
                    <template slot-scope="scope">
                        <div v-if="scope.row.talentPortrait.length > 0">
                            <el-tag size="small" style="margin-left: 5px;" v-for="(item, index) in scope.row.talentPortrait"
                                :key="index" :type="item.type">
                                {{ item.name }}
                            </el-tag>
                        </div>
                    </template>
                </el-table-column> -->
            </el-table>
        </el-dialog>
    </div>
</template>
  
<script>
import { listPosition, addPosition, delPosition, getPositionDetail, updatePosition } from '@/api/system/position.js'
import { listResume } from '@/api/system/resume.js'

export default {
    name: "Role",
    dicts: ['sys_normal_disable'],
    data() {
        var checkAge = (rule, value, callback) => {
            if (!value) {
                return callback(new Error('年龄不能为空'));
            }
            setTimeout(() => {
                if (value < 18) {
                    callback(new Error('必须年满18岁'));
                } else if (value > 70) {
                    callback(new Error('不能超过70岁'));
                } else {
                    callback();
                }
            }, 500);
        };
        var checkWorkExperience = (rule, value, callback) => {
            if (!value) {
                return callback(new Error('工作经验不能为空'));
            }
            setTimeout(() => {
                if (value < 0) {
                    callback(new Error('工作经验不能小于0'));
                } else if (value > 30) {
                    callback(new Error('请设置合理的工作经验'));
                } else {
                    callback();
                }
            }, 500);
        };
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            willDeleteIds: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 角色表格数据
            roleList: [],
            // 弹出层标题
            title: "",
            resumeTitle: "",
            // 是否显示弹出层
            open: false,
            resumeOpen: false,
            resumeOpenList: [],
            // 是否显示弹出层（数据权限）
            openDataScope: false,
            menuExpand: false,
            menuNodeAll: false,
            deptExpand: true,
            deptNodeAll: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                name: [
                    { required: true, message: "岗位名称不能为空", trigger: "blur" }
                ],
                age: [
                    { required: true, validator: checkAge, trigger: "blur" }
                ],
                education: [
                    { required: true, message: "学历不能为空", trigger: "blur" }
                ],
                salaryRange: [
                    { required: true, message: "薪资不能为空", trigger: "blur" }
                ],
                workExperience: [
                    { required: true, validator: checkWorkExperience, trigger: "blur" }
                ],
                skills: [
                    { required: true, message: "特长技能不能为空", trigger: "blur" }
                ],
                descriptions: [
                    { required: true, message: "岗位描述不能为空", trigger: "blur" }
                ],
            },
            educationOptions: [{
                value: '初中',
                label: '初中'
            }, {
                value: '中专',
                label: '中专'
            }, {
                value: '高中',
                label: '高中'
            }, {
                value: '大专',
                label: '大专'
            }, {
                value: '本科',
                label: '本科'
            }, {
                value: '硕士',
                label: '硕士'
            }, {
                value: '博士',
                label: '博士'
            }],
            isRefresh: false,
        };
    },
    created() {
        this.getList();
    },
    methods: {
        /** 查询角色列表 */
        getList() {
            this.loading = true;
            listPosition(this.queryParams).then(res => {
                console.log(res);
                this.total = res.total
                this.roleList = res.rows
                this.loading = false;
                this.isRefresh = false
            })
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            if (this.$refs.menu != undefined) {
                this.$refs.menu.setCheckedKeys([]);
            }
            this.menuExpand = false,
                this.menuNodeAll = false,
                this.deptExpand = true,
                this.deptNodeAll = false,
                this.form = {
                    age: undefined,
                    education: undefined,
                    name: undefined,
                    salaryRange: [5000, 10000],
                    skills: undefined,
                    workExperience: undefined,
                    delFlag: "0",
                    createTime: undefined,
                    id: undefined,
                    descriptions: undefined,
                    creatBy: "admin"
                };
            this.resetForm("form");
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加岗位";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            getPositionDetail(row.id).then(res => {
                this.form = res.data
                this.form.salaryRange = [Number(res.data.salaryRange.split('~')[0]), Number(res.data.salaryRange.split('~')[1])]

                const regex = /(\d+)年/;
                const match = res.data.workExperience.match(regex);
                this.form.workExperience = Number(match[1])

                this.open = true;
                this.title = "修改岗位";
            })
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    let range = this.form.salaryRange
                    let ragneStr, workStr
                    if (range[0]) {
                        ragneStr = `${range[0]}~${range[1]}`
                    } else {
                        ragneStr = `0~${range[1]}`
                    }
                    workStr = `${this.form.workExperience}年`
                    let commitForm = JSON.parse(JSON.stringify(this.form))
                    commitForm.workExperience = workStr
                    commitForm.salaryRange = ragneStr

                    if (commitForm.id) {
                        updatePosition(commitForm).then(res => {
                            if (res.code == 200) {
                                this.$modal.msgSuccess("修改成功");
                                this.open = false;
                                this.getList();
                            }
                        })
                    } else {
                        addPosition(commitForm).then(res => {
                            if (res.code == 200) {
                                this.$modal.msgSuccess("新增成功");
                                this.open = false;
                                this.getList();
                            }
                        })
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const roleIds = row.id;
            const that = this
            this.$modal.confirm('是否确认删除编号为"' + roleIds + '"的数据项？').then(function () {
                delPosition(roleIds).then(() => {
                    that.getList();
                    that.$modal.msgSuccess("删除成功");
                })
            }).catch(() => {

            })
        },
        handleSelectionChange(selection) {
            this.willDeleteIds = []
            if (selection.length > 1) {
                this.multiple = false
                selection.forEach(el => {
                    this.willDeleteIds.push(el.id)
                })
            } else {
                this.multiple = true
                this.willDeleteIds = []
            }
        },
        handleMutipleDelete() {
            const that = this
            this.$modal.confirm('是否确认删除这' + this.willDeleteIds.length + '项数据？').then(function () {
                delPosition(that.willDeleteIds).then(() => {
                    that.getList();
                    that.$modal.msgSuccess("删除成功");
                })
            }).catch(() => {

            })
        },
        refresh() {
            this.isRefresh = true
            this.getList()
        },
        handleSee(row) {
            // console.log(row);
            listResume({
                pageNum: 1,
                pageSize: 10,
                matchingPosition: row.name
            }).then(res => {
                if (res.total == 0) {
                    this.$message.error('暂无简历!')
                } else {
                    this.resumeOpen = true
                    this.resumeTitle = "查看简历"
                    this.resumeOpenList = res.rows
                    console.log(res.rows);
                }
            })
        },
        sortChange(col) {
            let arr = JSON.parse(JSON.stringify(this.roleList));
            if (col.order == 'ascending') {
                arr.sort((a, b) => {
                    let order = {
                        '博士': 7,
                        '硕士': 6,
                        '本科': 5,
                        '大专': 4,
                        '高中': 3,
                        '中专': 2,
                        '初中': 1
                    };
                    if (order[a[col.prop]] < order[b[col.prop]]) {
                        return -1;
                    }
                    if (order[a[col.prop]] > order[b[col.prop]]) {
                        return 1;
                    }
                    return 0;
                })
            } else if (col.order == 'descending') {
                arr.sort((a, b) => {
                    let order = {
                        '博士': 1,
                        '硕士': 2,
                        '本科': 3,
                        '大专': 4,
                        '高中': 5,
                        '中专': 6,
                        '初中': 7
                    };
                    if (order[a[col.prop]] < order[b[col.prop]]) {
                        return -1;
                    }
                    if (order[a[col.prop]] > order[b[col.prop]]) {
                        return 1;
                    }
                    return 0;
                })
            }
            this.roleList = arr
        }
    }
};
</script>